package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    //根据用户名查询用户信息,包括用户的角色和角色关联的权限
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//根据用户名查询用户表
        if(user == null){
            return null;
        }
        Integer userId = user.getId();
        //根据用户id查询关联的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        if(roles != null && roles.size() > 0){
            //遍历角色集合，查询每个角色关联的权限
            for (Role role : roles) {
                Integer roleId = role.getId();//角色id
                //根据角色id查询关联的权限
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if(permissions != null && permissions.size() > 0){
                    //角色关联权限集合
                    role.setPermissions(permissions);
                }
            }
            //用户关联角色集合
            user.setRoles(roles);
        }

        return user;
    }

    /**
     * 查询全部关键字
     * @return
     */
    @Override
    public User findAll() {
        //获取到全部权限
        List<Permission> permissions = permissionDao.findAll();
        //获取到全部菜单
        List<Menu> menus = menuDao.findAll();
        // 封装入user返回
        User user = new User();
        user.setMenus(menus);
        user.setPermissions(permissions);
        return user;
    }
    //根据用户名获取动态菜单展示
    @Override
    public List<Menu> getMenuList(String username) {
        LinkedHashSet<Menu> menus = null;
        User user = userDao.getMenuMap(username);
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            menus = role.getMenus();
        }
        ArrayList<Menu> list = new ArrayList<>(menus);
        List<Menu> menuList = buildMenuTree(list, 0);
        return menuList;
    }
    @Override
    public Boolean updatePassword(String username, String oldPassword, String newPassword) {
        //            使用MD5对新密码加密
        String password1 = MD5Utils.md5(oldPassword);
        //            数据库存的旧密码的MD5加密密码
        String password2 = userDao.findUserPassword(username);
        //            使用MD5对新密码加密
        String MD5Password = MD5Utils.md5(newPassword);
        if (password1.equals(password2)) {
            BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
            String password = bpe.encode(newPassword);
            userDao.updatePassword(username, password, MD5Password);
            return true;
        }else{
            return false;
        }

    }

    private List<Menu> buildMenuTree(List<Menu> menuList, Integer pid) {
        List<Menu> treeList = new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getParentMenuId().equals(pid)) {
                menu.setChildren(buildMenuTree(menuList, menu.getId()));
                treeList.add(menu);
            }

        }
        return treeList;
    }

    @Override
    public Result add(User user) {
        try {
            userDao.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user != null){
            List<Integer> roleIds = user.getRoleIds();
            if (roleIds != null){
                for (Integer roleId : roleIds) {
                    userDao.setUserAndRole(user.getId(),roleId);
                }
            }
            return new Result(true,"新增用户成功");
        }
        return new Result(false,"新增用户失败");
    }

    @Override
    public Result findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
//        Page<User> page = userDao.findPage(queryPageBean.getQueryString());
        Page<User> page = userDao.findPage(queryPageBean.getQueryString());
        return  new Result(true,"查询用户成功",new PageResult(page.getTotal(),page.getResult()));


    }

    @Override
    public Result edit(User user) {
        userDao.update(user);
        userDao.deleteBeforeAssociation1(user.getId());
        List<Integer> roleIds = user.getRoleIds();
        for (Integer roleId : roleIds) {
            userDao.setUserAndRole(user.getId(),roleId);
        }
        return new Result(true,"修改成功");
    }


    public Result findById(Integer id) {
        User user = userDao.findById(id);
        List<Integer> roleIds = userDao.findUserAndRoleId(id);
        List<User> allUser = userDao.findAllUser();
        if (user != null){
            user.setRoleIds(roleIds);
            user.setUsers(allUser);
        }
        return new Result(true,"查询成功",user);
    }

    @Override
    public Result findRole() {
        List<Role> roleList = userDao.findRole();
        return new Result(true,"查询成功", roleList);
    }
    @Override
    public Result findAll1() {
        List<User> userList = userDao.findAllUser();
        return new Result(true,"查询用户成功",userList);
    }
    @Override
    public Result deleteById(User user) {
        List<Integer> userAndRoleIds = userDao.findUserAndRoleId(user.getId());
        for (Integer userAndRoleId : userAndRoleIds) {
            userDao.deleteBeforeAssociation(userAndRoleId);
        }
        userDao.deleteById(user.getId());
        return new Result(true,"删除用户成功");
    }
}
